<template>
    <div class="app-container">
        <p>抽取项目</p>
        <div style="margin-bottom: 6px;"></div>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="iNumber" label="项目名称">
            </el-table-column>
            <el-table-column prop="iName" label="项目编号">
            </el-table-column>
            <el-table-column prop="bType" label="业务类型" :formatter="typeFormatter">
            </el-table-column>
        </el-table>

        <div style="margin-top: 10px;"></div>
        <el-descriptions class="margin-top" title="抽取申请" style="color: #409eff;" :column="2" border>
            <el-descriptions-item>
                <template slot="label">
                    抽取申请编号
                </template>
                编码自动生成
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    招标项目名称
                </template>
                <template>
                    {{ form.pName }}
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    资格审查方式
                </template>
                <template slot="default">
                    <el-radio label="1" v-model="form.reviewType">资格预审</el-radio>
                    <el-radio label="2" v-model="form.reviewType">资格后审</el-radio>
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    专家确定方式
                </template>
                <template slot="default">
                    <el-radio label="1" v-model="form.confMethod">随机抽取</el-radio>
                    <el-radio label="2" v-model="form.confMethod">直接指定</el-radio>
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    评标开始时间
                </template>
                <template>
                    <el-date-picker v-model="form.startTime" type="datetime" id="input-common1" placeholder="请选择评标开始时间"
                        value-format="yyyy-MM-dd HH:mm:ss" default-time="09:00:00">
                    </el-date-picker>
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    评标结束时间
                </template>
                <template>
                    <el-date-picker v-model="form.endTime" type="datetime" id="input-common1" placeholder="请选择评标结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss" default-time="09:00:00">
                    </el-date-picker>
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    专家人数
                </template>
                <template>
                    <el-input v-model="form.count" id="input-common3" disabled="disabled" placeholder="根据抽取专家人数生成" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    采购方代表人数
                </template>
                <template>
                    <el-input v-model="form.purchaseCount" id="input-common4" disabled="disabled"
                        placeholder="根据采购方人数生成" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    评标地点
                </template>
                <template>
                    <el-input v-model="form.address" id="input-common6" />
                </template>
            </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 50px;"></div>

        <div v-if="form.confMethod == 1">
            <p>抽取条件设置 &nbsp; &nbsp; &nbsp; <el-button type="primary" size="mini" @click="addCondition">添加</el-button>
            </p>
            <el-table :data="conditionTable" stripe style="width: 100%">
                <el-table-column label="序号" type="index" width="100" align="center">
                </el-table-column>
                <el-table-column prop="profession" label="评标专业">
                </el-table-column>
                <el-table-column prop="count" label="抽取人数">
                </el-table-column>
                <el-table-column prop="address" label="地区">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="deleteCondition(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <div>
            <div style="margin-top: 50px;"></div>
            <p>录入采购方代表 &nbsp; &nbsp; &nbsp; <el-button type="primary" size="mini" @click="addPurchase">添加</el-button>
            </p>
            <el-table :data="purchaseTable" stripe style="width: 100%">
                <el-table-column prop="pName" label="姓名" align="center">
                </el-table-column>
                <el-table-column prop="idCard" label="身份证号" align="center">
                </el-table-column>
                <el-table-column prop="phone" label="联系方式" align="center">
                </el-table-column>
                <el-table-column prop="sex" label="性别" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="deletePurchase(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>



        <div v-if="form.confMethod == 1">
            <div style="margin-top: 50px;"></div>
            <p>设置回避单位 &nbsp; &nbsp; &nbsp; <el-button type="primary" size="mini" @click="addAvoidUnit">添加</el-button>
            </p>
            <el-table :data="avoidUnitTable" stripe style="width: 100%">
                <el-table-column prop="unitName" label="单位名称">
                </el-table-column>
                <el-table-column prop="rCode" label="统一社会信用代码">
                </el-table-column>
                <el-table-column prop="representativeReason" label="回避原因" :formatter="reasonFormatter">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="deleteAvoidUnit(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div v-if="form.confMethod == 1">
            <div style="margin-top: 50px;"></div>
            <p>设置回避专家 &nbsp; &nbsp; &nbsp; <el-button type="primary" size="mini" @click="addAvoidExpert">添加</el-button>
            </p>
            <el-table :data="avoidExpertTable" stripe style="width: 100%">
                <el-table-column prop="zjName" label="专家姓名">
                </el-table-column>
                <el-table-column prop="idCard" label="身份证号">
                </el-table-column>
                <el-table-column prop="phone" label="联系方式">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="deleteAvoidExpert(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>

        <!-- 非弹窗专家table -->
        <div v-if="form.confMethod == 2">
            <div style="margin-top: 50px;"></div>
            <p>选择专家 &nbsp; &nbsp; &nbsp; <el-button type="primary" size="mini" @click="addAvoidExpert">添加</el-button>
            </p>
            <el-table :data="expertTable" stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="zjName" label="专家姓名" align="center">
                </el-table-column>
                <el-table-column prop="idCard" label="身份证" align="center">
                </el-table-column>
                <el-table-column prop="profession" label="专业" align="center">
                    <template slot-scope="scope">
                        <span v-for="(item, index) in scope.row.profession" :key="index">
                            {{ item }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="区域" align="center">
                </el-table-column>
                <el-table-column prop="phone" label="联系方式" align="center">
                </el-table-column>
            </el-table>
        </div>

        <el-dialog title="抽取条件" style="width: 70%;margin-left: 19%;" :visible.sync="conditionOpen">

            <el-form ref="conditionForm" :rules="conditionRules" style="margin-left: -40px;" :model="conditionForm"
                label-width="120px">
                <!-- 数据库存储的是名而不是数字,所以判断要用名判断 -->
                <el-form-item label="专业" prop="profession">
                    <el-select v-model="conditionForm.profession" placeholder="请选择专业" style="width: 340px;">
                        <el-option v-for="dict in dict.type.industry_type" :key="dict.value" :label="dict.label"
                            :value="dict.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- 数据库存储的是名而不是数字,所以判断要用名判断 -->
                <el-form-item label="区域" prop="address">
                    <el-select v-model="conditionForm.address" placeholder="请选择区域" style="width: 340px;">
                        <el-option v-for="dict in dict.type.province" :key="dict.value" :label="dict.label"
                            :value="dict.label">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="抽取人数" prop="count">
                    <el-input-number style="width: 340px;" v-model="conditionForm.count" size="medium" :min="1"
                        :max="10" label="抽取人数"></el-input-number>
                </el-form-item>

                <div class="useButton" style="margin-left: 69%;">
                    <el-button type="primary" @click="sureCondition">确定</el-button>
                    <el-button @click="cancel">取消</el-button>
                </div>
            </el-form>

        </el-dialog>

        <el-dialog title="采购方代表" style="width: 85%;margin-left: 14%;" :visible.sync="purchaseOpen">
            <el-form ref="purchaseForm" :rules="purchaseRules" style="margin-left: -40px;" :model="purchaseForm"
                label-width="120px">
                <el-form-item label="姓名" prop="pName">
                    <el-input v-model="purchaseForm.pName"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-radio label="1" v-model="purchaseForm.sex">男</el-radio>
                    <el-radio label="2" v-model="purchaseForm.sex">女</el-radio>
                </el-form-item>

                <el-form-item label="身份证号" prop="idCard">
                    <el-input v-model="purchaseForm.idCard"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="purchaseForm.phone"></el-input>
                </el-form-item>


                <div class="useButton" style="margin-left: 72%;">
                    <el-button type="primary" @click="sutePurchase">确定</el-button>
                    <el-button @click="cancel">取消</el-button>
                </div>

            </el-form>
        </el-dialog>

        <el-dialog title="回避单位" style="width: 70%;margin-left: 19%;" :visible.sync="avoidUnitOpen">
            <el-form ref="avoidUnitForm" :rules="avoidUnitRules" style="margin-left: -30px;" :model="avoidUnitForm"
                label-width="120px">
                <el-form-item label="社会信用代码" prop="rCode">
                    <el-input v-model="avoidUnitForm.rCode" style="width: 80%;"></el-input>
                </el-form-item>

                <el-form-item label="单位名称" prop="unitName">
                    <el-input v-model="avoidUnitForm.unitName" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="回避原因" prop="representativeReason">
                    <el-radio v-model="avoidUnitForm.representativeReason"
                        v-for="dict in dict.type.representative_reason" :key="dict.value" :label="dict.value">
                        {{ dict.label }}
                    </el-radio>
                </el-form-item>

                <div class="useButton" style="margin-left: 70%;">
                    <el-button type="primary" @click="sureSupplier">确定</el-button>
                    <el-button @click="cancel">取消</el-button>
                </div>
            </el-form>
        </el-dialog>

        <el-dialog title="专家" style="width: 130%;margin-left: -17%;" :visible.sync="avoidExpertOpen">
            <el-form ref="form" :model="avoidUnitForm" style="margin-top: -30px;">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="姓名" prop="zjName">
                            <el-input v-model="queryParams.zjName" style="width: 260px;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="专业" prop="specialized">
                            <el-input v-model="queryParams.specialized" style="width: 260px;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-button type="primary">查询</el-button>
                        <el-button>重置</el-button>
                    </el-col>
                </el-row>

                <div style="margin-bottom: 10px; margin-left: 570px;margin-top: -10px">

                </div>
            </el-form>

            <el-table v-loading="dialogExpertDataLoading" highlight-current-row :data="dialogExpertData" stripe
                style="width: 100%;overflow: auto" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="zjName" label="专家姓名" align="center">
                </el-table-column>
                <el-table-column prop="idCard" label="身份证" align="center">
                </el-table-column>
                <el-table-column prop="profession" label="专业" align="center">
                    <template slot-scope="scope">
                        <span v-for="(item, index) in scope.row.profession" :key="index">
                            {{ item }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="区域" align="center">
                </el-table-column>
                <el-table-column prop="phone" label="联系方式" align="center">
                </el-table-column>
            </el-table>
            <div style="margin-left: 86%; margin-top: 10px;">
                <el-button type="primary" size="small" @click="handleConfirm">确认</el-button>
                <el-button size="small" @click="">取消</el-button>
            </div>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getDialogExpertData" />
        </el-dialog>

        <div style="margin-top: 20px;margin-bottom: 80px;margin-left: 84%;">
            <el-button type="primary" @click="addApplications">
                提交
            </el-button>
            <el-button @click="cancelApplications">
                取消
            </el-button>
        </div>

    </div>
</template>

<script>
import { getTender, getDialogExpertData, addApplications } from '@/api/system/purchase'

export default {
    dicts: ["business_type", "province", "industry_type", "representative_reason"],
    data() {
        return {
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                specialized: '',
                zjName: ''
            },
            total: 0,
            tableData: [],//抽取项目
            conditionTable: [],//抽取条件
            purchaseTable: [],//采购方代表
            avoidUnitTable: [],//回避单位
            avoidExpertTable: [],//回避专家
            expertTable: [],//非弹窗专家
            dialogExpertDataLoading: true,//回避专家弹窗加载
            form: {
                applicationNumber: '',
                confMethod: '1',
                reviewType: '1',
                count: 0,
                purchaseCount: 0,

            },//抽取申请
            avoidUnitOpen: false, //回避单位弹窗
            avoidExpertOpen: false,//回避专家弹窗
            purchaseOpen: false,//采购方代表弹窗
            conditionOpen: false,//条件弹窗
            conditionForm: {},//弹窗--条件表单
            purchaseForm: {
                sex: "1"
            },//弹窗--采购方表单
            avoidUnitForm: {},//回避单位表单
            dialogExpertData: [],//弹窗--回避专家
            selectedRows: [],//选中的专家数据
            //抽取的规则
            conditionRules: {
                profession: [
                    { required: true, message: '请选择专业', trigger: 'change' }
                ],
                address: [
                    { required: true, message: '请选择区域', trigger: 'change' }
                ],
                count: [
                    { required: true, message: '请输入抽取人数', trigger: 'blur' }
                ]
            },
            //采购方的规则
            purchaseRules: {
                pName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                idCard: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
                ]
            },
            //回避单位的规则
            avoidUnitRules: {
                rCode: [
                    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
                ],
                unitName: [
                    { required: true, message: '请输入单位名称', trigger: 'blur' }
                ],
                representativeReason: [
                    { required: true, message: '请选择回避原因', trigger: 'change' }
                ]
            }
        }
    },
    methods: {
        //蒙版
        openFullScreen2() {
            return new Promise((resolve) => {
                const loading = this.$loading({
                    lock: true,
                    text: '3', // 初始文本为 3  
                    spinner: '>>', // 不显示旋转图标  
                    background: 'rgba(0, 0, 0, 0.7)',
                    customClass: 'loading-custom' // 添加自定义类  
                });

                let count = 3; // 倒计时的初始值  
                const interval = setInterval(() => {
                    count--; // 每次减少 1  
                    loading.text = count.toString(); // 更新加载文本  

                    if (count <= 1) {
                        clearInterval(interval); // 当倒计时到达 1 时清除定时器  
                        setTimeout(() => {
                            loading.close(); // 1 秒后关闭加载  
                            resolve(); // 关闭后解决 Promise  
                        }, 1000); // 这里设置为 1 秒，倒计时到 1 后再关闭  
                    }
                }, 1000); // 每秒更新一次  
            });
        },
        //业务类型
        typeFormatter(row, column, cellValue, index) {
            let label = "";
            this.dict.type.business_type.forEach(rse => {
                if (cellValue === Number(rse.value)) {
                    label = rse.label;
                    return;
                }
            })
            return label;
        },
        //招标项目获取
        getTender(iNumber) {
            getTender(iNumber).then(res => {
                this.form.pName = res.data.iName;
                this.tableData.push(res.data);
            })
        },
        //添加回避专家
        addAvoidExpert() {
            this.avoidExpertOpen = true;
            this.getDialogExpertData();
        },
        //添加回避单位
        addAvoidUnit() {
            this.avoidUnitOpen = true;
        },
        //添加采购方代表
        addPurchase() {
            this.purchaseOpen = true;
        },
        //添加条件
        addCondition() {
            this.conditionOpen = true;
        },
        //确定抽取条件
        sureCondition() {
            this.$refs.conditionForm.validate(valid => {
                if (valid) {
                    this.conditionTable.push(this.conditionForm);
                    this.form.count += this.conditionForm.count;

                    this.conditionForm = {};
                    this.conditionOpen = false;
                } else {
                    this.$message({
                        message: '请填写完整',
                        type: 'warning'
                    });
                    return;
                }
            });
        },
        //确定回避单位
        sureSupplier() {
            this.$refs.avoidUnitForm.validate(valid => {
                if (valid) {
                    let exists = false;
                    // 表单验证通过，执行提交逻辑
                    this.avoidUnitTable.forEach(item => {
                        if (item.rCode == this.avoidUnitForm.rCode) {
                            this.$message({
                                message: '此单位已存在',
                                type: 'warning'
                            });
                            exists = true;
                            return; // 退出 forEach 循环
                        }
                    })
                    if (!exists) {
                        this.avoidUnitTable.push(this.avoidUnitForm);
                        this.avoidUnitForm = {};
                        this.avoidUnitOpen = false;
                    }

                } else {
                    // 表单验证失败，提示用户
                    return false;
                }
            });
        },
        //确定采购方
        sutePurchase() {
            this.$refs.purchaseForm.validate(valid => {
                if (valid) {
                    // 检查身份证号是否已存在
                    const idCardExists = this.purchaseTable.some(item => item.idCard === this.purchaseForm.idCard);
                    if (idCardExists) {
                        this.$message({
                            message: '此身份证号已存在',
                            type: 'warning'
                        });
                    } else {
                        this.purchaseTable.push({ ...this.purchaseForm });
                        this.form.purchaseCount += 1;
                        this.purchaseForm = { pName: '', sex: '1', idCard: '', phone: '' };
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                        this.purchaseOpen = false;
                    }
                } else {
                    this.$message({
                        message: '请填写完整信息',
                        type: 'warning'
                    });
                    return false;
                }
            });
        },
        //通用取消按钮
        cancel() {

        },
        //弹窗回避专家选中(多选框))
        handleSelectionChange(selection) {
            // 更新选中的行
            this.selectedRows = selection;
        },
        handleConfirm() {
            if (this.form.confMethod == 1) {
                // 过滤掉已经被选中的项
                const newSelection = this.selectedRows.filter(row => !this.avoidExpertTable.some(avoidRow => this.isSameRow(avoidRow, row)));
                // 将新选中的项添加到 avoidExpertTable
                newSelection.forEach(row => this.avoidExpertTable.push(row));
                // 更新 dialogExpertData，移除已经添加到 avoidExpertTable 的数据
                this.dialogExpertData = this.dialogExpertData.filter(row => !newSelection.some(selectedRow => this.isSameRow(selectedRow, row)));
            } else {
                const newSelection = this.selectedRows.filter(row => !this.expertTable.some(avoidRow => this.isSameRow(avoidRow, row)));
                newSelection.forEach(row => this.expertTable.push(row));
                // 更新 dialogExpertData，移除已经添加到 avoidExpertTable 的数据
                this.dialogExpertData = this.dialogExpertData.filter(row => !this.expertTable.some(selectedRow => this.isSameRow(selectedRow, row)));
                this.form.count += 1;
            }


            // 清空选中的行
            this.selectedRows = [];
            this.avoidExpertOpen = false;
        },
        isSameRow(row1, row2) {
            // 根据你的数据结构定义比较逻辑
            return row1.idCard === row2.idCard;
        },
        //获得专家列表
        getDialogExpertData() {
            getDialogExpertData(this.queryParams).then(res => {
                this.dialogExpertDataLoading = false;
                this.dialogExpertData = res.rows;
                this.total = res.total;
            })
        },
        //回避原因转化
        reasonFormatter(row, column, cellValue, index) {
            let label = "";
            this.dict.type.representative_reason.forEach(rse => {
                if (cellValue == Number(rse.value)) {
                    label = rse.label;
                    return;
                }
            })
            return label;
        },
        addApplications() {
            this.form.iNumber = this.$route.query.iNumber;
            this.avoidExpertTable.forEach(ele => {
                ele.expertName = ele.zjName;
            })
            let form = {};
            if (this.form.confMethod == 1) {
                form = {
                    application: this.form,
                    condition: this.conditionTable,
                    purchase: this.purchaseTable,
                    avoidExpert: this.avoidExpertTable,
                    avoidUnit: this.avoidUnitTable,
                }
            } else {
                form = {
                    application: this.form,
                    purchase: this.purchaseTable,
                    committee: this.expertTable
                }
            }
            addApplications(form).then(() => {
                this.openFullScreen2().then(() => {
                    this.$router.push({ path: '/tender/enterProject', query: { iNumber: this.$route.query.iNumber, flag: '1' } });
                });
            })
        },
        //关闭当前页面
        cancelApplications() {
        },

        deleteCondition(index) {
            this.conditionTable.splice(index, 1);
        },
        deletePurchase(index) {
            this.purchaseTable.splice(index, 1);
        },
        deleteAvoidUnit(index) {
            this.avoidUnitTable.splice(index, 1);
        },
        deleteAvoidExpert(row) {
            this.avoidExpertTable = this.avoidExpertTable.filter(item => item.idCard != row.idCard);
            this.selectedRows = this.selectedRows.filter(item => item.idCard != row.idCard);
        },
    },
    mounted() {
        const iNumber = this.$route.query.iNumber;
        this.getTender(iNumber);
    },
}
</script>
<style scoped>
.loading-custom .el-loading-text {
    font-size: 100px !important;
    /* 使用 !important 强制应用样式 */
    /* 调整字体大小 */
    color: white !important;
    /* 字体颜色 */
    text-align: center;
    /* 文本居中 */
    line-height: 1.5;
    /* 行高，确保文本垂直居中 */
}
</style>